package com.atguigu.eduservice.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionHandler.MyException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public EduSubjectService eduSubjectService;

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    //无参
    public SubjectExcelListener() {
    }

    // 要注意判断分类是否已经存在了，避免重复添加
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new MyException(20001, "添加失败");
        }

        String oneSubjectName = subjectData.getOneSubjectName();
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", oneSubjectName).eq("parent_id", "0");
        EduSubject one = eduSubjectService.getOne(queryWrapper);


        if (one == null) {
            one = new EduSubject();
            one.setTitle(oneSubjectName).setParentId("0");
            eduSubjectService.save(one);
        }

        String parentId = one.getId();

        QueryWrapper<EduSubject> queryWrapper1 = new QueryWrapper<>();
        String twoSubjectName = subjectData.getTwoSubjectName();
        queryWrapper1.eq("title", twoSubjectName).eq("parent_id", parentId);
        EduSubject two = eduSubjectService.getOne(queryWrapper1);

        if (two == null) {
            two = new EduSubject();
            two.setTitle(twoSubjectName).setParentId(parentId);
            eduSubjectService.save(two);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
